//
//  YijuWebViewController.m
//  YiJuZhangShou2.0
//
//  Created by 冷悦 on 16/3/27.
//  Copyright © 2016年 Mr.X. All rights reserved.
//

#import "YijuWebViewController.h"
//#import "UIView+Share.h"
#import "UIAlertControllerUtil.h"
#import "YiJuWebShareViewModel.h"

@interface YijuWebViewController () <UIWebViewDelegate, NetworkingBaseManagerAPISuccessCallbackDelegate,NetworkingBaseManagerValidator>

@property (nonatomic, strong) UIWebView *webView;

@property (nonatomic, copy) NSString *htmlAddress;

@property (nonatomic, strong) NetworkingBaseManager *manager;

@property (nonatomic, strong) YiJuWebShareViewModel *yiJuWebShareViewModel;

@end

@implementation YijuWebViewController
#pragma mark - Initialize
- (instancetype)initWithHtmlId:(NSUInteger)htmlId
                  htmlTypeName:(MagazineType)htmlTypeName
                     projectId:(NSInteger)projectId
                  Introduction:(NSString *)introduction
                  andHtmlTitle:(NSString *)title{
    if (self = [super init]) {
        self.htmlId = htmlId;
        self.htmlTypeName = htmlTypeName;
        self.introduction = introduction;
        self.htmlTitle = title;
        self.projectId = projectId;
    }
    
    return self;
}

- (instancetype)initWithUrlAddress:(NSString *)urlAddress
                      withUrlTitle:(NSString *)urlTitle
                  withIntroduction:(NSString *)urlIntroduction{
    if (self = [super init]) {
        self.htmlAddress = urlAddress;
        self.htmlTitle = urlTitle;
        self.introduction = urlIntroduction;
        [self loadWeb];
    }
    return self;
}

#pragma mark - Life Circle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = self.htmlTitle == nil ? @"宜居" : self.htmlTitle;
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self setupNavigation];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

/**
 *  根据js返回参数调用相关的操作
 *
 *  @param command 操作名称
 *  @param param   操作的参数
 */
- (void)updateActionWithCmd:(NSString *)command withParam:(NSString *)param{
    if ([command isEqualToString:@"updateBaseURL"]) {
        [AppContext sharedInstance].baseUrl = param;
    }
    //后续命令可以自己继续添加
}

#pragma mark - NetworkingBaseManagerAPISuccessCallbackDelegate
//UIWebView 读取html界面，并发送自己的userId以及appVersion给前端
- (void)manager:(NetworkingBaseManager *)manager callAPIDidSuccessWithParams:(NSDictionary *)responseParams{
    NSDictionary *dataDic = [responseParams objectForKey:@"data"];
    NSString *httpURL = [dataDic objectForKey:@"url"];
    _htmlAddress = httpURL;
    [self loadWeb];
}

#pragma mark - Delegate NetworkingBaseManagerValidator
- (BOOL)isCorrectWithCallbackData:(NSDictionary *)data{
    //    NSAssert(NO, @"未重写判断网络返回数据正确性代理事件(BaseViewModel)");
    NSInteger stateCode = [[data objectForKey:@"stateCode"] integerValue];
    if (stateCode == 100||stateCode == 101|| stateCode == 102|| stateCode == 103) {
        return YES;
    }else{
        [UIAlertControllerUtil generateInfoControllerWithTitle:[NSString stringWithFormat:@"%ld",stateCode] message:[data objectForKey:@"stateMessage"]];
        return NO;
    }
}

#pragma mark - UIWebViewDelegate
#ifndef kYijuWebViewCommand
#define kYijuWebViewCommand @"appCommand"
#endif
//js提交请求到oc，如果带有相关的参数，进行参数操作
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(nonnull NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType{
    NSString *absoluteString = [[request URL] absoluteString];
    NSArray *components = [absoluteString componentsSeparatedByString:@":"];
    
    if (components.count > 1 && [(NSString *)[components firstObject] isEqualToString:kYijuWebViewCommand]) {
        NSString *command = (NSString *)components[1];
        NSString *params = (NSString *)components[2];
        [self updateActionWithCmd:command withParam:params];
        return NO;
    }
    
    return YES;
}

#pragma mark - Event Response
- (void)shareAction:(UIBarButtonItem *)barItem{
#ifndef kYijuWebViewShareTitle
#define kYijuWebViewShareTitle @"宜居分享"
#endif
    if (self.htmlAddress != nil) {
        NSString *introduction = self.introduction == nil ? kYijuWebViewShareTitle:self.introduction;
        NSString *title = self.htmlTitle == nil ? self.title : kYijuWebViewShareTitle;
//        [self.webView shareWithContent:introduction
//                                 Title:title
//                              shareURL:self.htmlAddress];
        self.yiJuWebShareViewModel.magazineType = self.htmlTypeName;
        self.yiJuWebShareViewModel.magazineId = self.htmlId;
        [self.yiJuWebShareViewModel loadRequest];
    }
}

#pragma mark - Private
- (void)loadWeb{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_htmlAddress]];
    request.HTTPMethod = @"POST";
    NSUInteger userId = [AppContext sharedInstance].userId;
    NSString *appVersion = [AppContext sharedInstance].appVersion;
    NSString *postBody = [NSString stringWithFormat:@"userId=%ld&appVersion=%@", (unsigned long)userId, appVersion];
    [request setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
    [self.webView loadRequest:request];
}

/**
 *  获取相关的网页apiName
 *
 *  @param htmlId       html界面的id
 *  @param htmlTypeName html的类型
 *
 *  @return 产生post请求
 */
- (NSString *)generateAPINameWithHtmlId:(NSUInteger)htmlId
                          withProjectId:(NSInteger)projectId
                        andHTMLTypeName:(MagazineType)htmlTypeName{
    NSString *api = [NSString stringWithFormat:@"projects/%ld/users/%ld/webType/%ld/webs/%ld",(long)projectId,(long)[AppContext sharedInstance].userId,(unsigned long)htmlTypeName, (unsigned long)htmlId];
    NSString *apiName = [[RequestGenerator sharedInstance] generateCommonApiWithName:api];
    return apiName;
}

//配置navigationController
- (void)setupNavigation{
    if (self.htmlTypeName != IndianaActivity && self.htmlTypeName != AuctionActivity && self.htmlTypeName != GroupBuyActivity) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                                                                              target:self
                                                                                              action:@selector(shareAction:)];
    }
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
}

#pragma mark - Public
/**
 *  发送请求，获取html的地址
 */
- (void)loadHTMLRequest{
    NSAssert(self.htmlId != 0, @"HTML Id Should Not Be 0 Unknown Type");
    NSAssert(self.htmlTypeName != 0, @"HTML Type Should Not Be nil Unknown HTML");
    
    _manager = [NetworkingManagerFactory generateSHA256Manager];
    _manager.successDelegate = self;
    _manager.validator = self;
    _manager.requestType = HTTP_GET;
    NSString *apiName = [self generateAPINameWithHtmlId:self.htmlId withProjectId:self.projectId andHTMLTypeName:self.htmlTypeName];
    _manager.apiName = apiName;
    [_manager loadRequest];
}

#pragma mark - Getters
-(UIWebView *)webView{
    if (_webView == nil) {
        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-64)];
        _webView.delegate = self;
        [self.view addSubview:_webView];
    }
    
    return _webView;
}

- (YiJuWebShareViewModel *)yiJuWebShareViewModel{
    if (_yiJuWebShareViewModel == nil) {
        _yiJuWebShareViewModel = [YiJuWebShareViewModel new];
    }
    return _yiJuWebShareViewModel;
}

@end
